<template>
  <div>
    <!-- 搜索指定教师 -->
    <div class="mytest search-input" >
      <el-select 
        v-if="$store.state.role=='superAdmin'"
        placeholder="选择搜索教师所属学校"
        v-model="searchSchool"
        class="account-search"
        id="account-search-border"
      >
        <el-option
          v-for="item in majors"
          :key="item.id"
          :label="item.schoolName"
          :value="item.id"
          @click.native="search"
        ></el-option>
      </el-select>
      <el-input
        type="text"
        placeholder="查询教师用户名"
        class="account-search"
        id="account-search-border"
        @keyup.enter.native="search"
        @blur="search"
        v-model="inputName"
        clearable
      >
        <span 
          slot="prefix" 
          class="el-icon-search account-search-icon"
        ></span>
      </el-input>
      <el-input
        type="text"
        placeholder="请输入要查询教师姓名"
        class="account-search"
        id="account-search-border"
        @keyup.enter.native="search"
        @blur="search"
        v-model="inputNickName"
        clearable
      >
        <span 
          slot="prefix" 
          class="el-icon-search account-search-icon"
        ></span>
      </el-input>
      <!-- 添加教师 -->
      <el-button 
        class="add-button"
        size="medium" 
        icon="el-icon-plus"
        @click="add"
      >添加教师</el-button>
      <!-- 判断是新增还是修改信息 -->
      <el-dialog
        :title="isAdd ? '新增' : '编辑'"
        :visible="dialogVisible"
        @update:visible="dialogCancel"
      >
        <!-- 输出信息框 -->
        <el-form 
          ref="ruleForm" 
          :model="formData" 
          class="info-change"
          label-width="100px"
        >
        <!-- :label-position="left"-->
          <template v-for="(item, index) of columnList">
            <el-form-item
              v-if="
                (!isAdd && item.edit) ||
                  (isAdd &&
                    item.prop != 'password'  &&
                    item.prop != 'schoolName' &&
                    item.prop != 'userId')
              "
              :key="index"
              :label="(item.prop != 'password' ? (item.label + ':') : '修改密码:')"
              :prop="item.prop"
              :rules="item.rules"
              class="info-input"
            >
              <el-input
                v-if="item.type == 'text'"
                v-model="formData[item.prop]"
              ></el-input>
              <el-switch 
                v-if="item.type == 'password'"
                v-model="isChangePassword"
              ></el-switch>
            </el-form-item>
          </template>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogCancel" class="cancel-button">取 消</el-button>
          <el-button
           :loading="submitLoading" 
           @click="submit"
           class="confirm-button"
          >确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div>
      <!-- 数据展示 -->
      <el-main>
        <el-table
          :data="tableData"
          v-loading="tableLoading"
          stripe
        >
          <template v-for="item in columnList">
            <!-- 输出需要的信息栏 -->
            <el-table-column
              v-if="item.prop != 'password'"
              :key="item.prop"
              :prop="item.prop"
              :label="item.label"
            >
            </el-table-column>
          </template>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <!-- 编辑信息 -->
              <el-button 
                size="small" 
                @click="edit(row)"
                icon="el-icon-edit-outline"
                class="btn_primary"
              >编辑</el-button>
              <!-- 防止删除误触 -->
              <!-- 删除账号 -->
              <el-button
                :loading="row.removelaoding"
                slot="reference"
                size="small"
                icon="el-icon-delete"
                @click="removeConfirm(row)"
                class="btn_danger"
              >删除</el-button>
            </template>
          </el-table-column>
          <el-table-column>
          </el-table-column>
        </el-table>

        <!-- 数据展示方式 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 40]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize"
          class="change-page"
        ></el-pagination>
      </el-main>
    </div>
  </div>
</template>
<script>
const columnList = [
  {
    label: "教师ID",
    type: "text",
    prop: "userId",
    //是否可以编辑渲染表单
    edit: false,
   
  },
  {
    label: "用户名",
    type: "text",
    prop: "username",
    edit: true,
     rules: [{ required: true, message: "请输入用户名", trigger: "blur" }]
  },
  {
    label: "教师所在学校名称",
    type: "text",
    prop: "schoolName",
    edit: false
  },
  {
    label: "昵称",
    type: "text",
    prop: "nickname",
    edit: true,
    rules: [{ required: true, message: "请输入昵称", trigger: "blur" }]
  },
  {
    label: "联系方式",
    type: "text",
    prop: "phone",
    edit: true,
    rules: [{ required: true, message: "请输入联系方式", trigger: "blur" },
            { type : "string" ,pattern : /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,message: "请正确填写您的手机号码！" }
    ]
  },
  {
    label: "密码",
    type: "password",
    prop: "password",
    edit: true
  }
];
import {
  addUserList,
  update,
  getUserInfoByRole,
  getUSerInfoByNickOrName,
  deleteTeacher,
  getUserBySchoolId
} from "@/api/teacher";
import {getSchools} from "@/api/school";
export default {
  data() {
    return {
      currentPage: 1,
      pagesize: 10,
      totalSize: 0,
      tableData:[],
      removelaoding: false,
      dialogVisible: false,
      userInfo: {},
      tableLoading: false,
      formLabelWidth: "120px",
      formData: {},
      isAdd: true,
      submitLoading: false,
      inputName: "",
      inputNickName:"",
      columnList,
      isChangePassword:false,
      searchSchool:null,
      majors:[{id:null,schoolName:'全部学校'}],
    };
  },
  created() {
    // this.getTableData();
    //获取当前用户信息
    this.userInfo = JSON.parse(localStorage.getItem("user"));
    this.getTableData();
    console.log(this.userInfo);
    getSchools({pageNum:1,pageSize:1000})
      .then((res)=>{
         res.data.forEach((item) => {
            this.majors.push(item);
          });
        console.log(this.majors);
      });
    
  },
  methods: {
    getTableData() {
      this.tableLoading = true;
      //当前登录的人的角色
      let searchSchool=(this.userInfo.roleName=='superAdmin'?this.searchSchool:this.userInfo.schoolId);
      getUSerInfoByNickOrName({
        role: "TEACHER",
        pageNum: this.currentPage,
        pageSize: this.pagesize,
        usernameKey: this.inputName,
        nicknameKey:this.inputNickName,
        schoolId:searchSchool
      })
        .then(res => {
          //得到所有教师的列表
          res.data.forEach(element => {
            element.removelaoding = false;
          });
          this.tableData = res.data;
          this.totalSize = res.total;
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    //触发添加教师事件
    add() {
      this.dialogVisible = true;
      //this.$refs.ruleForm.clearValidate();
      this.isAdd = true;
    },
    //触发编辑教师信息事件
    edit(data) {
      this.formData = {...data};
      this.isAdd = false;
      this.isChangePassword=false;
      // this.$refs.ruleForm.clearValidate();
      this.dialogVisible = true;
    },
    //取消消息框编辑模式
    dialogCancel() {
      (this.formData = {}), (this.dialogVisible = false);
    },
    //搜索指定教师
    search() {
      this.tableLoading = true;
      let searchSchool=(this.userInfo.roleName=='superAdmin'?this.searchSchool:this.userInfo.schoolId);
      getUSerInfoByNickOrName({ 
        role: "TEACHER", 
        //用户输入的相关搜索信息
        usernameKey: this.inputName,
        nicknameKey:this.inputNickName,
        schoolId:searchSchool,
        pageNum: 1,
        pageSize: this.pagesize
      })
        .then(res => {
          //得到所有教师的列表
          res.data.forEach(element => {
            element.removelaoding = false;
          });
          this.tableData = res.data;
          this.totalSize = res.total;
          console.log(res)
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    //确认是否删除
    removeConfirm(row) {
      this.$confirm( '删除后不可恢复','是否删除该教师？', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        center: true
      }).then(() => {
        this.remove(row);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //删除账号
    remove(row) {
      row.removelaoding = true;
      deleteTeacher({ userId: row.userId })
        .then(res => {
          //后台没传id过来
          this.$message.success("删除成功");
        })
        .finally(() => {
          row.removelaoding = false;
          this.getTableData();
        });
    },
    //导出密码
    creatPasswordFile(data, filename) {
      var uri = 'data:application/vnd.ms-TXT;charset=utf-8,' + encodeURIComponent(data);
      var link = document.createElement("a");
      link.href = uri;
      link.download = `${filename}`; 
      link.click();
    },
    //生成密码
    generate(){
      var pwdArray = [   //密码元素
        ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
         'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'],
        ['0','1','2','3','4','5','6','7','8','9'],
        ['!','@','#','$','%','^','&','*']
      ];
      var pwd = [];
      var len = Math.floor(Math.random() * 5 + 8);  //规定密码位数至少8位
      for(let i = 0; i < len; i++){
        let sortArray = pwdArray[i % 3];            //规定密码必须包含字母、数字、特殊字符
				let pwdIndex = Math.floor(Math.random() * sortArray.length);  //pwdIndex为sortArray元素内的随机索引
				pwd.push(sortArray[pwdIndex]);
      }
	    while( len > 0){
        len--;
	      let index = Math.floor(Math.random() * len);
	      let temp = pwd[index];
	      pwd[index] = pwd[len];
	      pwd[len] = temp;
	    }
      return pwd.join("");
    },
    //密码提示
    open(data) {
      this.$alert(data, '该账号密码为', {
        confirmButtonText: '确定',
        callback: action => {
          this.$message({
            type: 'info',
            message: `action: ${ action }`
          });
        }
      });
    },
    //提交新增或修改信息
    submit() {
      this.$refs.ruleForm
        .validate(valid => {
          if (valid) {
            this.submitLoading = true;
            if (this.isAdd) {
              this.formData.password = this.generate();
              this.formData.role = "TEACHER";
              this.formData.status=true;
              this.formData.gender="FEMALE"
              this.formData.schoolId=this.userInfo.schoolId;
              //this.formData.schoolName=this.$store.state.schoolName;
              let formArray = [];
              formArray.push(this.formData);
              addUserList(formArray) //请求体是数组
                .then(res => {
                  this.$message.success("新增成功");
                  this.open(this.formData.password);// 提示框展示密码
                  this.creatPasswordFile(this.formData.password, "password_"+this.formData.role+"_"+this.formData.username+".txt");//导出密码
                  console.log(res.code);
                  this.getTableData();
                }).catch(err =>{
                  //console.log(error.code);
                  console.log(err.response);
                  this.$message.error(err.response.data.message);
                })
                .finally(() => {
                  this.submitLoading = false;
                  this.dialogCancel();
                });
            } else {
              this.formData.role = "TEACHER";
              this.formData.status = true;
              this.formData.gender = "FEMALE";
              if(this.isChangePassword){
                this.formData.password = this.generate();
              }
              delete this.formData.classList;
              delete this.formData.createdTime;
              delete this.formData.updatedTime;
              delete this.formData.removelaoding;
              Object.keys(this.formData).forEach((item) => {
                if(this.formData[item]==null){
                  delete this.formData[item];
                }
              })
              delete this.formData.schoolName;
              update(this.formData)
                .then(res => {
                  this.$message.success("修改成功");
                  if(this.isChangePassword){
                    this.open(this.formData.password);// 提示框展示密码
                    this.creatPasswordFile(this.formData.password, "password_"+this.formData.role+"_"+this.formData.username+".txt");//导出密码
                  }
                  this.getTableData();
                })
                .finally(() => {
                  this.submitLoading = false;
                  this.dialogCancel();
                });
            }
          }
        })
    },
    handleSizeChange(size) {
      this.pagesize = size;
      //每页下拉显示数据
      this.getTableData();
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getTableData();
    }
  }
};
</script>
<style scoped>
.title {
  font-size: 32px;
  color: #409eff;
  margin-bottom: 30px;
  font-weight: bold;
}
</style>
<style type="text/css">
.mytest {
  height: 42px;
  flex-direction: row;
  justify-content: flex-start;
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  flex-direction: row;
  -webkit-box-pack: start;
  -ms-flex-pack: start;
  justify-content: flex-start;
  flex-wrap: nowrap;
}
.el-dialog__header{
  background-color:#5b8bff;
  text-align: left;
  height: 20px;
}
.el-dialog__title {
  color: #f4f4f5;
  font-size: 18px;
}
.el-dialog__headerbtn .el-dialog__close {
  color: #f4f4f5;
}
.info-change{
  padding: 3% 6%;
  border-bottom:2px solid #c0c4cc8f;
}
.el-form-item__label{
  text-align: center;
}
.el-dialog__footer{
  text-align: center;
}
.el-message-box__btns .el-button--default, .cancel-button{
  border-radius: 20px;
  height: 35px;
  background-color: #909399;
  color: #f4f4f5;
}
.el-message-box__btns .el-button--primary,.confirm-button{
  border-radius: 20px;
  height: 35px;
  background-color: #5b8bff;
  color: #f4f4f5;
}
.el-message-box__title{
  color: #5b8bff;
  font-size: 22px;
  margin-bottom:-10px ;
}
.search-input{
  margin-bottom:-20px;
  display:flex;
}
.search-input .el-input__icon{
  margin-top: -7px !important; 
}
.search-input .el-select__caret{
  height: 200% !important;
  margin-top: -11px !important;
}
.account-search{
  width: 210px; 
  margin-left:20px;
}
#account-search-border {
  border-radius: 25px;  
  height: 25px;
}
.account-search-icon{
  font-size:15px; 
  margin:6px 4px; 
  color:#5b8bff;
}
.add-button{
  width:150px;
  background:#5b8bff; 
  color:#f4f4f5; 
  border-radius: 340px;
  height: 25px; 
  padding-top:4px;
  position: absolute;
  right: 80px;
}
.info-input{
  text-align:left;
}
.change-page{
  margin-top:15px
}
.el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf {
  border-bottom:none;
  text-align:center;
}
.el-table th.el-table__cell.is-leaf{
  color: #7986a6;
  font-weight: 500;
}
.el-table td.el-table__cell{
  padding:3px 0;
}
</style>
